package com.jd.filter;

import com.alibaba.fastjson.JSONObject;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.net.ServerSocket;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author wangshuping
 * @version 1.0
 * @date 2021/11/14 23:59
 */
@Component
public class TokenFilter implements GlobalFilter, Ordered {


    public TokenFilter() {
        System.out.println("init");
    }

    @Value("${auth.allowNoTokenAccessUrls:/admin/login,/login,/admin/validate/code,/validate/code,/authorization-server/oauth/token,/admin-service/login}")
    private List<String> allowNoTokenAccessUrls;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        if (allowNoTokenAccess(exchange)) {
            return chain.filter(exchange);
        }

        String token = getToken(exchange);
        if (StringUtils.isEmpty(token)) {
            return buildUNAuthorizationResult(exchange);
        }

        if (false) {
            return buildUNAuthorizationResult(exchange);
        }

        return chain.filter(exchange);
    }

    private String getToken(ServerWebExchange exchange) {
        String token = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if (StringUtils.isEmpty(token) || token.trim().isEmpty()) {
            return null;
        }
        return token.replace("bearer ", "");
    }

    private Mono<Void> buildUNAuthorizationResult(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error", "unauthorized");
        jsonObject.put("error_description", "invalid_token");
        DataBuffer dataBuffer = response.bufferFactory().wrap(jsonObject.toString().getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Flux.just(dataBuffer));
    }

    private boolean allowNoTokenAccess(ServerWebExchange exchange) {
        return allowNoTokenAccessUrls.contains(exchange.getRequest().getURI().getPath());
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
